// 返回记录时间
export function getSerializeDateTime() {
  const date = new Date()
  let month: number | string = date.getMonth() + 1
  if (month < 10) {
    month = `0${month}`
  }
  let day: number | string = date.getDate()
  if (day < 10) {
    day = `0${day}`
  }
  let hours: number | string = date.getHours()
  if (hours < 10) {
    hours = `0${hours}`
  }
  let minutes: number | string = date.getMinutes()
  if (minutes < 10) {
    minutes = `0${minutes}`
  }
  let second: number | string = date.getSeconds()
  if (second < 10) {
    second = `0${second}`
  }
  return `${date.getFullYear()}-${month}-${day}${hours}${minutes}${second}`
}

export function cipher() {
  const salt = process.env.APP_BUILD_SALT
  const textToChars = (text: string) => text.split('').map(c => c.charCodeAt(0));
  const byteHex = (n: any) => ("0" + Number(n).toString(16)).substring(("0" + Number(n).toString(16)).length - 2);
  const applySaltToChar = (code: any) => textToChars(salt).reduce((a, b) => a ^ b, code);
  return (text: string) => text.split('')
    .map(textToChars)
    .map(applySaltToChar)
    .map(byteHex)
    .join('');
}

export function decipher() {
  const salt = process.env.APP_BUILD_SALT
  const textToChars = (text: string) => text.split('').map((c: string) => c.charCodeAt(0));
  const applySaltToChar = (code: any) => textToChars(salt).reduce((a: number, b: number) => a ^ b, code);
  return (encoded: string) => encoded.match(/.{1,2}/g)!
    .map((hex: string) => parseInt(hex, 16))
    .map(applySaltToChar)
    .map((charCode: number) => String.fromCharCode(charCode))
    .join('');
}

export function encode(str: string): string {
  const fn = cipher()
  return fn(str)
}

export function decode(str: string) {
  const fn = decipher()
  return fn(str)
}
